//
//  WHHomeController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2018/12/29.
//  Copyright © 2018 邓伟浩. All rights reserved.
//

#import "WHHomeController.h"
#import "WHHomeTopView.h"
#import "WHExpressOperationView.h"
#import "WHHomeMenuCell.h"

#import "WHTransReconizeController.h" // 面单识别
#import "WHExpressSignController.h" // 快递签收
#import "WHExpressInController.h" // 快递入库

#import "WHScanController.h"
#import "WHRootNavigationController.h"

#import "WHSearchResultController.h"

@interface WHHomeController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) WHHomeTopView *topView;
@property (nonatomic, strong) NSArray *tipsArray;
@property (nonatomic, strong) NSArray *tipsImageArray;
@property (nonatomic, strong) NSArray *classNameArray;

@end

@implementation WHHomeController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self selectNumber];
}

- (void)initParams {
    _tipsArray = @[@"快递合作", @"短信中心", @"入库失败", @"问题件处理"];
    _tipsImageArray = @[@"home_coopreation_icon", @"home_message_icon", @"home_in_icon", @"home_problem_icon"];
    _classNameArray = @[@"WHCoopExpressController", @"WHMsgCenterController", @"WHInFailureController", @"WHQuestionDealController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHidenNaviBar = YES;
    
    [self initParams];
    [self setUpHomeUI];
}

- (void)setUpHomeUI {
    [self setUpTopView];
    [self setUpBottomView];
}

- (void)setUpTopView {
    UIImageView *homeBackImageView = [[UIImageView alloc] init];
    homeBackImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:homeBackImageView];
    homeBackImageView.image = IMAGE_NAMED(@"home_back");
    [homeBackImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self.view);
        make.height.mas_equalTo(kRealwidth(238));
    }];
    
    WHHomeTopView *homeTopView = [[WHHomeTopView alloc] init];
    [self.view addSubview:homeTopView];
    [homeTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self.view);
        make.height.mas_equalTo(kRealwidth(155)+kStatusBarHeight);
    }];
    kWeakSelf(self);
    homeTopView.beginSearch = ^(NSString * _Nonnull searchText) {
        [weakself searchByText:searchText];
    };
    homeTopView.beginScan = ^{
        [weakself beginScan];
    };
    _topView = homeTopView;
}

- (void)setUpBottomView {
    UIScrollView *backScrollView = [[UIScrollView alloc] init];
    backScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:backScrollView];
    
    [backScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(_topView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(-kTabBarHeight);
        }
    }];
    
    CGFloat buttonWidth = (KScreenWidth-3*KNormalSpace)/2;
    
    UIView *operationBackView = [[UIView alloc] init];
    operationBackView.layer.cornerRadius  = 12;
    operationBackView.layer.masksToBounds = NO;
    operationBackView.layer.shadowColor = HexColor(@"002233").CGColor;
    operationBackView.layer.shadowOffset = CGSizeMake(0, 0);
    operationBackView.layer.shadowOpacity = 0.1;
    operationBackView.layer.shadowRadius = 5;
    
    operationBackView.backgroundColor = KWhiteColor;
    [backScrollView addSubview:operationBackView];
    
    [operationBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(backScrollView.mas_left).offset(KNormalSpace);
        make.top.mas_equalTo(backScrollView.mas_top).offset(KNormalSpace);
        make.width.mas_equalTo(KScreenWidth-2*KNormalSpace);
        make.height.mas_equalTo(buttonWidth);
    }];
    
    
    WHExpressOperationView *expressInOV = [[WHExpressOperationView alloc] init];
    expressInOV.tipsImage = IMAGE_NAMED(@"home_reco");
    expressInOV.tipsText = @"面单识别";
    [operationBackView addSubview:expressInOV];
    [expressInOV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(buttonWidth);
        make.left.mas_equalTo(operationBackView.mas_left);
        make.top.mas_equalTo(operationBackView.mas_top);
    }];
    kWeakSelf(self);
    expressInOV.opreation = ^{
        WHExpressInController *expressIn = [[WHExpressInController alloc] init];
        [weakself.navigationController pushViewController:expressIn animated:YES];
        
//        WHTransReconizeController *transReco = [[WHTransReconizeController alloc] init];
//        [weakself.navigationController pushViewController:transReco animated:YES];
    };
    
    WHExpressOperationView *expressSignOV = [[WHExpressOperationView alloc] init];
    expressSignOV.tipsImage = IMAGE_NAMED(@"home_expressSign");
    expressSignOV.tipsText = @"快递签收";
    [operationBackView addSubview:expressSignOV];
    [expressSignOV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(buttonWidth);
        make.left.mas_equalTo(expressInOV.mas_right).offset(KNormalSpace);
        make.top.mas_equalTo(operationBackView.mas_top);
    }];
    expressSignOV.opreation = ^{
        WHExpressSignController *expressSignC = [[WHExpressSignController alloc] init];
        [weakself.navigationController pushViewController:expressSignC animated:YES];
    };
    
    CGFloat itemWidth = (KScreenWidth-2*KNormalSpace-1)/2;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(itemWidth, kRealwidth(120));
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 1;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    UICollectionView *menuSelectView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    menuSelectView.backgroundColor = CViewBgMainColor;
    menuSelectView.dataSource = self;
    menuSelectView.delegate = self;
//    menuSelectView.scrollEnabled = NO;
    ViewRadius(menuSelectView, 12);
    
    UIView *shadowView = [[UIView alloc] init];
    shadowView.layer.cornerRadius  = 12;
    shadowView.layer.shadowColor = HexColor(@"002233").CGColor;
    shadowView.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView.layer.shadowOpacity = 0.1;
    shadowView.layer.shadowRadius = 5;
    shadowView.clipsToBounds = NO;
    shadowView.backgroundColor = KWhiteColor;
    [backScrollView addSubview:shadowView];
    [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(KNormalSpace);
        make.right.mas_equalTo(self.view.mas_right).offset(-KNormalSpace);
        make.height.mas_equalTo(kRealwidth(240)+1);
        make.top.mas_equalTo(operationBackView.mas_bottom).offset(KNormalSpace);
    }];
    
    [menuSelectView registerClass:[WHHomeMenuCell class] forCellWithReuseIdentifier:NSStringFromClass([WHHomeMenuCell class])];
    
    [shadowView addSubview:menuSelectView];
    [menuSelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(shadowView);
    }];
    
    [self.view layoutIfNeeded];
    backScrollView.clipsToBounds = NO;
    backScrollView.contentSize = CGSizeMake(KScreenWidth, shadowView.bottom);
}

#pragma mark —————— UICollectionViewDataSource & UICollectionViewDelegate ——————

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WHHomeMenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WHHomeMenuCell class]) forIndexPath:indexPath];
    if (indexPath.row < 4) {
        cell.tipsLabel.text = _tipsArray[indexPath.row];
        cell.tipsImageView.image = IMAGE_NAMED(_tipsImageArray[indexPath.row]);
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UIViewController *vc = [[NSClassFromString(_classNameArray[indexPath.row]) alloc] init];
    if (vc == nil) {
        
    } else {
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - —————— 事件 ——————
- (void)beginScan {
    [self.view endEditing:YES];
    WHScanController *scan = [[WHScanController alloc] init];
    WHRootNavigationController *navi = [[WHRootNavigationController alloc] initWithRootViewController:scan];
    [self presentViewController:navi animated:YES completion:nil];
    kWeakSelf(self);
    scan.outPutStr = ^(NSString *dataStr) {
        [weakself.topView showSearch];
        [weakself gridOutputStr:dataStr];
    };
}

#pragma mark - —————— 处理扫描结果 ——————

- (void)gridOutputStr:(NSString *)dataStr {
    
    if ([self isBarCode:dataStr]) {
        self.topView.searchText = dataStr;
        [self searchByText:dataStr];
        
        return;
    }
    [WHView showAlertwithTitle:nil message:@"无法识别!" okAction:nil cancelAction:nil];
}

- (BOOL)isBarCode:(NSString *)checkedNumString {
    NSString *barCodeRegex = @"^[a-zA-Z0-9]+$";
    NSPredicate *barCodePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", barCodeRegex];
    return [barCodePredicate evaluateWithObject:checkedNumString];
}

#pragma mark - —————— 接口 ——————
- (void)selectNumber {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_selectNumber);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                NSString *intoStatus = retDict[@"intoStatus"];
                NSString *outStatus = retDict[@"outStatus"];
                NSString *waitNumber = retDict[@"waitNumber"];
                _topView.intoStatus = intoStatus;
                _topView.outStatus = outStatus;
                _topView.waitNumber = waitNumber;
                
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)searchByText:(NSString *)text {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_searchExpressCompany);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          text, @"waybillNum",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                NSDictionary *retDict = responseObject[@"retobj"];
                
                WHExpressResult *result = [WHExpressResult modelWithDictionary:retDict];
                
                if (result.Shippers.count == 0) {
                    [WHView showHudMsg:@"搜索结果不存在"];
                } else {
                    WHSearchResultController *searchResult = [[WHSearchResultController alloc] init];
                    searchResult.result = result;
                    [self.navigationController pushViewController:searchResult animated:YES];
                }
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
